/**
 * Created by Administrator on 2017/1/15.
 */
var pomelo = require('pomelo');
var config = require('./config');

var MJ = require('../MJ/MJ');
var MJRoom = require('../MJ/room').MJRoom;

var Const = require('./const');
var SubCode = require('../subCode');
var gameUtil = require("../../../util/gameUtil");
exports.HSMJRoom = MJRoom.extend({

    init: function (rid, creator, msg) {
        this._super(rid, creator, msg);
        //this.round = 1;
        this._LZCard = 0;               //赖子牌
        this._HZFCLZG = this.getOption('RULE') == 1 ? true : false;    //红中发财赖子杠          

        this._LPTask = [];  //亮牌队列
        this._submitLPTask = [];
        this.giftcost = 0;
        this.huIndex = 0;

        this.setSaveReplay(true);
    },
    rest: function () {
        this._LZCard = 0;
        this._LPTask = [];  //亮牌队列
        this._submitLPTask = [];
        this.giftcost = 0;
        this.huIndex = 0;
    },
    checkInit: function () {
        return this._super();
    },

    getLZCard: function () {
        return this._LZCard;
    },
    getHZFCLZG: function () {
        return this.getOption('rule') == 1;
    },
    getFS: function () {
        return this._FS;
    },
    /******************************************************************
     * 重载的接口
     ******************************************************************/

    getRoomConfig: function () {
        var cfg = this._super();
        cfg.destroyWaitTime = 120;
        cfg.respDestroyIgnore = 1;
        return cfg;
    },

    getInfo: function () {
        var info = this._super();
        return info;
    },

    getRoundInfo: function () {
        var info = this._super();
        return info;
    },

    getReconnectInfo: function (rePlayer) {
        var info = this._super(rePlayer);
        if (this.getHZFCLZG()) {
            info.lz = [this.getLZCard(), MJ.ZI.HZ, MJ.ZI.FC];
        } else {
            info.lz = [this.getLZCard(), MJ.ZI.HZ];
        }



        if (this._LPTask.length != 0) {
            var flag = false;
            this._LPTask.forEach(function (v) {
                if (rePlayer.getIndex() == v.Player.getIndex()) {
                    flag = true;
                    info.needLP = v.count;

                }
            });
            if (!flag) {
                info.waitLP = true;
            }

        }

        return info;
    },

    onBeforeStartNewRound: function () {
        this._super();
        this.rest();
    },

    onAfterStartNewRound: function () {
        this._super();
        this.SetLZP();
        this.preStartPlay();
    },
    //设置赖子
    _setLZCard: function () {
        var lz = this.getRandomCard();

        if (this.getHZFCLZG()) {
            if (lz == MJ.ZI.HZ || lz == MJ.ZI.FC || lz == MJ.ZI.BB) {
                this._LZCard = MJ.ZI.BB;

            } else {
                this._LZCard = lz;
            }
        } else {
            if (lz == MJ.ZI.HZ) {
                this._LZCard = MJ.ZI.FC;
            } else if (lz == MJ.ZI.FC) {
                this._LZCard = MJ.ZI.BB;
            } else if (lz == MJ.ZI.BB) {
                this._LZCard = MJ.ZI.FC;
            } else {
                this._LZCard = lz;
            }
        }
    },
    //发牌
    preStartPlay: function (player, msg, card) {

        // this.SetLZP();
    },

    startPlay: function () {
        this._sendHangupTask(this._startPlay);
    },

    _startPlay: function () {
        this._changeCurPlay(this.getDealerIndex());
        //检查摸牌后玩家的挂起任务
        this._doCheckNewCardHangupTask();
    },

    onBeforePlayCard: function (player, msg, card) {
        if (this._LPTask.length != 0) {
            return SubCode.MJ_SELECT_COLOR_STATUS_ERROR;
        }
    },
    checkCurPlayHangupTask: function () {
        var player = this.getCurPlayer();

        var gangArray = player.checkGang();
        if (gangArray.length > 0) {
            this._hangupTask.addGangTask(player.getIndex(), gangArray);
        }

    },


    onAfterGangTask: function (player, card, gangTask, gangInfo) {
        //点杠判断几句话
        var gang = gangTask.gangArray[0].gang;
        if (gang == MJ.Gang.DIAN || gang == MJ.Gang.BA) {
            player._gangCount += 1;
            player._mingGangCount += 1;
            player.setFS('MG');
        } else if (gang == MJ.Gang.AN || gang == MJ.Gang.ANS) {
            player._angangCount += 1;
            player.setFS('AG');
        }
    },

    onAfterPengTask: function (player, card, pengTask) {
        player._pengCount += 1;

    },
    onAfterChiTask: function (player, card, chiTask) {
        player._chiCount += 1;

        var selectCard = chiTask.selectCard;
        //吃赖子加番

        if (selectCard == this.getLZCard() || (selectCard - 1) == this.getLZCard()
            || (selectCard - 2) == this.getLZCard()) {
            player.setFS('CLZ');
        }
    },
    //检查拿牌后玩家的挂起任务
    checkNewCardHangupTask: function () {
        var player = this.getCurPlayer();

        var huIndexs = [];
        var huPattern = player.checkHu();

        if (huPattern != Const.Pattern.NONE) {
            var rules = [];
            if (this.getCurGang()) {
                rules.push(Const.ScoreRule.GSH);
            }

            var card = player.getLastCard() || player.getInitLastCard();


            var task = {
                "card": card,
                "from": player.getIndex(),
                "pattern": huPattern,
                "playerIndex": player.getIndex()
            }
            if (this.countScore(task)) {

                this._hangupTask.addHuTask(player.getIndex(), card, player.getIndex(), huPattern, rules);
            } else {
                //this._hangupTask.addHuTask(player.getIndex(), card, player.getIndex(), Const.Pattern.NONE, rules);
            }


            huIndexs.push(player.getIndex());
        }

        var gangArray = player.checkGang();
        if (gangArray.length > 0) {

            this._hangupTask.addGangTask(player.getIndex(), gangArray);
        }

        huIndexs.forEach(function (eIndex) {
            var ePlayer = this.getPlayerByIndex(eIndex);
            if (ePlayer && ePlayer.isBaoTing()) {
                this._hangupTask.submitTask(eIndex, MJ.Task.HU);
            }
        }.bind(this));
    },

    checkPlayCardHangupTask: function (card) {
        this._checkPlayCardHangupTask(card);
    },

    _checkPlayCardHangupTask: function (card) {
        var curPlay = this.getCurPlay();
        var nextIndex = this.getNextIndex(curPlay);

        var curPlayer = this.getCurPlayer();

        var huIndexs = [];
        this.enumPlayers(function (eIndex, ePlayer) {
            if (eIndex != curPlay && !ePlayer.isRoundHu()) {
                if (!ePlayer.isPassHu() && ePlayer.getBaoTingPassHuTimes() < 1) {
                    var huPattern = ePlayer.checkHuWithCard(card);
                    if (huPattern != Const.Pattern.NONE) {
                        var rules = [];
                        if (ePlayer.isBaoTing()) {
                            if (ePlayer.isFirstHand() && ePlayer.getIndex() != this.getDealerIndex()) {
                                rules.push(Const.ScoreRule.DIHU);
                            } else {
                                rules.push(Const.ScoreRule.BT);
                            }
                        }

                        if (this.getCurGang() > 0) {
                            rules.push(Const.ScoreRule.GSP);
                        }

                        var task = {
                            "card": card,
                            "from": curPlay,
                            "pattern": huPattern,
                            "playerIndex": ePlayer.getIndex()
                        }
                        if (this.countScore(task)) {

                            this._hangupTask.addHuTask(ePlayer.getIndex(), card, curPlay, huPattern, rules);
                        } else {
                            //this._hangupTask.addHuTask(ePlayer.getIndex(), card, curPlay, Const.Pattern.NONE, rules);
                        }


                        //this._hangupTask.addHuTask(ePlayer.getIndex(), card, curPlay, huPattern, rules);
                        huIndexs.push(eIndex);
                    }
                }
                if (ePlayer.checkGangWithCard(card)) {

                    this._hangupTask.addGangTask(eIndex, [{ card: card, from: curPlay, gang: MJ.Gang.DIAN }]);
                }
                if (ePlayer.checkPengWithCard(card)) {
                    this._hangupTask.addPengTask(eIndex, card, curPlay);
                }
                if (eIndex == nextIndex) { // 下家可以吃牌
                    var maxCards = ePlayer.checkChiWithCard(card);
                    if (maxCards) {
                        this._hangupTask.addChiTask(eIndex, card, curPlay, maxCards);
                    }
                }
            }
        }.bind(this));

        huIndexs.forEach(function (eIndex) {
            var ePlayer = this.getPlayerByIndex(eIndex);
            if (ePlayer && ePlayer.isBaoTing()) {
                this._hangupTask.submitTask(eIndex, MJ.Task.HU);
            }
        }.bind(this));
    },
    //检查杠牌后的挂起任务
    checkGangHangupTask: function (playerIndex, gangInfo) {
        var card = gangInfo.card;
        if (gangInfo.type) {
            card = gangInfo.buCard;
        }

        var huIndexs = [];
        this.enumPlayers(function (eIndex, ePlayer) {
            if (eIndex != playerIndex && !ePlayer.isRoundHu() && !ePlayer.isPassHu() && ePlayer.getBaoTingPassHuTimes() < 1) {
                var huPattern = ePlayer.checkHuWithCard(card);
                if (huPattern != Const.Pattern.NONE) { // 抢杠
                    var rules = [];
                    rules.push(Const.ScoreRule.QG);

                    if (ePlayer.isBaoTing()) {
                        rules.push(Const.ScoreRule.BT);
                    }

                    var task = {
                        "card": card,
                        "from": playerIndex,
                        "pattern": huPattern,
                        "playerIndex": eIndex
                    }
                    if (this.countScore(task)) {

                        this._hangupTask.addHuTask(eIndex, card, playerIndex, huPattern, rules);
                    } else {
                        //this._hangupTask.addHuTask(eIndex, card, playerIndex, Const.Pattern.NONE, rules);
                    }

                    // this._hangupTask.addHuTask(eIndex, card, playerIndex, huPattern, rules);
                    huIndexs.push(eIndex);
                }
            }
        }.bind(this));
    },

    // checkGangTaskQG: function (task, gangInfo) {
    //     if (gangInfo.type) {
    //         return task.buCard ? true : false;
    //     } else {
    //         return gangInfo.gang == MJ.Gang.BA;
    //     }
    // },

    checkGangNewCard: function (gangInfo) {
        if (gangInfo.type) {
            if (gangInfo.buCard) {
                return true;
            }
            if (gangInfo.type == Const.SpecGang.XI || gangInfo.type == Const.SpecGang.YD || gangInfo.type == Const.SpecGang.JD) {
                return false;
            }
        }

        return true;
    },

    checkHuSettlement: function () {
        return true;
    },
    //门清
    isMQ: function (player) {
        if (player.getChiCount() > 0 || player.getDgangCount() > 0 || player.getPengCount() > 0) {
            return false;
        }
        return true;
    },
    _sumFs: function (player, flag) {
        var Fs = 0;
        ExObject.each(player._FS, function (k, v) {
            if (flag && k == 'YH') {
                return;
            }
            Fs += v;
        });
        return Fs;
    },
    //检查结算分数
    countScore: function (task) {


        this.enumPlayers(function (eIndex, ePlayer) {
            var sum = ePlayer._mingGangCount + ePlayer._chiCards.length + ePlayer._pengCards.length;
            if (sum >= 4) {
                ePlayer.setFS('SJH');
            } else if (sum == 3) {
                ePlayer.setFS('TJH');
            }
        }.bind(this));


        var playerIndex = task.playerIndex; //胡牌玩家位置
        var pattern = task.pattern;         //胡牌类型
        var card = task.card;               //
        var from = task.from;               //胡牌的来源位置
        var rules = task.rules;
        var huPlayer = this.getPlayerByIndex(playerIndex); //胡牌玩家

        //huPlayer._stat.huCard = card;
        var isMQ = this.isMQ(huPlayer);  //是否是门清
        var mqNum = 0;
        if (isMQ) {
            huPlayer._MQ = true;
            mqNum = -2; //门清每家结算加3
        }
        var isZM = (playerIndex == from); // 是否是自摸

        var Spattern = null; //简单规则


        if (pattern != Const.Pattern.NONE) {
            if (pattern == Const.Pattern.NORMAL) {
                Spattern = 'PH';
            } else if (pattern == Const.Pattern.PAIR ||
                pattern == Const.Pattern.PAIR7 ||
                pattern == Const.Pattern.JJH ||
                pattern == Const.Pattern.PAIR ||
                pattern == Const.Pattern.QIS) {
                Spattern = 'DH';
            } else if (pattern == Const.Pattern.QISPAIR ||
                pattern == Const.Pattern.QISJJH ||
                pattern == Const.Pattern.QISPAIR7 ||
                pattern == Const.Pattern.HHPAIR7 ||
                pattern == Const.Pattern.JPPH) {
                Spattern = 'SDH';
            }
        }
        if (Spattern == 'SDH' && isZM) {
            Spattern = 'YZM';
        }


        // this.enumPlayers(function (eIndex, ePlayer) {
        //     if (eIndex != playerIndex) {
        //         ePlayer.delFS('YH');
        //     }
        // }.bind(this));


        var winner = {
            'index': huPlayer,
            'FS': this._sumFs(huPlayer),
        };
        //winner['index']._stat.hCount += 1;
        var sumScore = [];
        if (isZM) {
            // huPlayer._isZM = true;
            var others = [];
            this.enumPlayers(function (eIndex, ePlayer) {
                if (eIndex != playerIndex && !ePlayer.isRoundHu()) {
                    others.push({
                        'index': ePlayer,
                        'FS': this._sumFs(ePlayer, true)
                    });
                }
            }.bind(this));


            if (Spattern == 'PH') {
                others.forEach(function (v) {
                    // v['index']._baseScore = 3;
                    var temp = (-3 + mqNum) * (Math.pow(2, winner['FS'] + v['FS']));
                    if (-temp > 80) {
                        temp = -80;
                    }
                    sumScore.push(temp)
                });
            } else if (Spattern == 'DH') {
                if (pattern == Const.Pattern.PAIR7) {
                    others.forEach(function (v) {
                        // v['index']._baseScore = 10;
                        var temp = (-10) * (Math.pow(2, winner['FS'] + v['FS']));
                        if (-temp > 80) {
                            temp = -80;
                        }
                        sumScore.push(temp)
                    });
                } else {
                    others.forEach(function (v) {
                        //v['index']._baseScore = 10;
                        var temp = (-10 + mqNum) * (Math.pow(2, winner['FS'] + v['FS']));
                        if (-temp > 80) {
                            temp = -80;
                        }
                        sumScore.push(temp)
                    });
                }
            } else if (Spattern == 'SDH') {
                if (pattern == Const.Pattern.QISPAIR7 || pattern == Const.Pattern.HHPAIR7) {
                    others.forEach(function (v) {
                        //v['index']._baseScore = 20;
                        var temp = (-20) * (Math.pow(2, winner['FS'] + v['FS']));
                        if (-temp > 80) {
                            temp = -80;
                        }
                        sumScore.push(temp);

                    });
                } else {
                    others.forEach(function (v) {
                        //v['index']._baseScore = 20;
                        var temp = (-20 + mqNum) * (Math.pow(2, winner['FS'] + v['FS']));
                        if (-temp > 80) {
                            temp = -80;
                        }
                        sumScore.push(temp);

                    });
                }
            } else if (Spattern == 'YZM') {
                if (pattern == Const.Pattern.QISPAIR7 || pattern == Const.Pattern.HHPAIR7) {
                    others.forEach(function (v) {
                        // v['index']._baseScore = 40;
                        var temp = (-40) * (Math.pow(2, winner['FS'] + v['FS']));
                        if (-temp > 80) {
                            temp = -80;
                        }
                        sumScore.push(temp)
                    });
                } else {
                    others.forEach(function (v) {
                        //   v['index']._baseScore = 40 + (-mqNum);
                        var temp = (-40 + mqNum) * (Math.pow(2, winner['FS'] + v['FS']));
                        if (-temp > 80) {
                            temp = -80;
                        }
                        sumScore.push(temp)
                    });
                }
            }
            if (sumScore.every(function (v) {
                return -v >= 80;
            })) {
                for (var i = 0; i < sumScore.length; ++i) {
                    sumScore[i] = -100;
                }
            }
            // var re = sumScore.reduce(function (a, b) {
            //     return a + b;
            // }, 0);
            // winner['index']._score = -re;

            // for (var j = 0; j < others.length; ++j) {
            //     others[j]['index']._score = sumScore[j];
            // }

        } else {
            var dpPlayer = this.getPlayerByIndex(from); //点炮玩家
            // dpPlayer._isdp = true;
            // dpPlayer._stat.dpCount += 1;
            var dp = {
                'index': dpPlayer,
                'FS': this._sumFs(dpPlayer, true)
            }
            var dpScore = 0;
            var others = [];
            this.enumPlayers(function (eIndex, ePlayer) {
                if (eIndex != playerIndex && !ePlayer.isRoundHu() && eIndex != from) {
                    others.push({
                        'index': ePlayer,
                        'FS': this._sumFs(ePlayer, true)
                    })
                }
            }.bind(this));

            if (Spattern == 'PH') {
                // dp['index']._baseScore = 2;
                var dpScore = (-2) * (Math.pow(2, winner['FS'] + dp['FS']));
                if (-dpScore > 80) {
                    dpScore = -80;
                }
                sumScore.push(dpScore);

                others.forEach(function (v) {
                    //  v['index']._baseScore = 1;
                    var temp = 0;
                    temp = (-1) * (Math.pow(2, winner['FS'] + v['FS']));
                    if (-temp > 80) {
                        temp = -80;
                    }
                    sumScore.push(temp);
                });
            } else if (Spattern == 'DH') {
                // dp['index']._baseScore = 10;
                var dpScore = (-10) * (Math.pow(2, winner['FS'] + dp['FS']))
                if (-dpScore > 80) {
                    dpScore = -80;
                }
                sumScore.push(dpScore);

                others.forEach(function (v) {
                    // v['index']._baseScore = 5;
                    var temp = (-5) * (Math.pow(2, winner['FS'] + v['FS']));
                    if (-temp > 80) {
                        temp = -80;
                    }
                    sumScore.push(temp);
                });
            } else if (Spattern == 'SDH') {
                //  dp['index']._baseScore = 20;
                var dpScore = (-20) * (Math.pow(2, winner['FS'] + dp['FS']))
                if (-dpScore > 80) {
                    dpScore = -80;
                }
                sumScore.push(dpScore);

                others.forEach(function (v) {
                    // v['index']._baseScore = 10;
                    var temp = (-10) * (Math.pow(2, winner['FS'] + v['FS']));
                    if (-temp > 80) {
                        temp = -80;
                    }
                    sumScore.push(temp);
                });
            } else if (Spattern == 'YZH') {
                //  dp['index']._baseScore = 40;
                var dpScore = (-40) * (Math.pow(2, winner['FS'] + dp['FS']))
                if (-dpScore > 80) {
                    dpScore = -80;
                }
                sumScore.push(dpScore);

                others.forEach(function (v) {
                    //  v['index']._baseScore = 20;
                    var temp = (-20) * (Math.pow(2, winner['FS'] + v['FS']));
                    if (-temp > 80) {
                        temp = -80;
                    }
                    sumScore.push(temp);
                });
            }

            if (sumScore.every(function (v) {
                return -v >= 80;
            })) {
                for (var i = 0; i < sumScore.length; ++i) {
                    sumScore[i] = -100;
                }
            }

        }

        if (this.getHZFCLZG()) {
            if (-sumScore.reduce(function (a, b) {
                return a + b;
            }, 0) > 15) {
                this.enumPlayers(function (eIndex, ePlayer) {
                    ePlayer.delFS('SJH');
                    ePlayer.delFS('TJH')
                }.bind(this));
                return true;
            }
        } else {
            if (-sumScore.reduce(function (a, b) {
                return a + b;
            }, 0) > 9) {
                this.enumPlayers(function (eIndex, ePlayer) {
                    ePlayer.delFS('SJH');
                    ePlayer.delFS('TJH')
                }.bind(this));
                return true;
            }
        }
        this.enumPlayers(function (eIndex, ePlayer) {
            ePlayer.delFS('SJH');
            ePlayer.delFS('TJH')

        }.bind(this));
        return false;

    },

    onSettlementHuTask: function (task) {

        //计算几句话
        this.enumPlayers(function (eIndex, ePlayer) {
            var sum = ePlayer._mingGangCount + ePlayer._chiCards.length + ePlayer._pengCards.length;
            if (sum >= 4) {
                ePlayer.setFS('SJH');
            } else if (sum == 3) {
                ePlayer.setFS('TJH')
            }
        }.bind(this));


        var playerIndex = task.playerIndex; //胡牌玩家位置
        var pattern = task.pattern;         //胡牌类型
        var card = task.card;               //
        var from = task.from;               //胡牌的来源位置
        var rules = task.rules;
        var huPlayer = this.getPlayerByIndex(playerIndex); //胡牌玩家

        this.huIndex = playerIndex;

        huPlayer._stat.huCard = card;
        var isMQ = this.isMQ(huPlayer);  //是否是门清
        var mqNum = 0;
        if (isMQ) {
            huPlayer._MQ = true;
            mqNum = -2; //门清每家结算加2
        }
        var isZM = (playerIndex == from); // 是否是自摸

        var Spattern = null; //简单规则


        if (pattern != Const.Pattern.NONE) {
            if (pattern == Const.Pattern.NORMAL) {
                Spattern = 'PH';
            } else if (pattern == Const.Pattern.PAIR ||
                pattern == Const.Pattern.PAIR7 ||
                pattern == Const.Pattern.JJH ||
                pattern == Const.Pattern.QIS
            ) {
                Spattern = 'DH';
            } else if (pattern == Const.Pattern.QISPAIR ||
                pattern == Const.Pattern.QISJJH ||
                pattern == Const.Pattern.QISPAIR7 ||
                pattern == Const.Pattern.HHPAIR7 ||
                pattern == Const.Pattern.JPPH) {
                Spattern = 'SDH';
            }
        }
        if (Spattern == 'SDH' && isZM) {
            Spattern = 'YZM';
        }


        this.enumPlayers(function (eIndex, ePlayer) {
            if (eIndex != playerIndex) {
                ePlayer.delFS('YH');
            }
        }.bind(this));


        var winner = {
            'index': huPlayer,
            'FS': this._sumFs(huPlayer),
        };
        winner['index']._stat.hCount += 1;
        var sumScore = [];
        if (isZM) {
            huPlayer._isZM = true;
            var others = [];
            this.enumPlayers(function (eIndex, ePlayer) {
                if (eIndex != playerIndex && !ePlayer.isRoundHu()) {
                    others.push({
                        'index': ePlayer,
                        'FS': this._sumFs(ePlayer)
                    });
                }
            }.bind(this));


            if (Spattern == 'PH') {
                others.forEach(function (v) {
                    v['index']._baseScore = 3 + (-mqNum);
                    var temp = (-3 + mqNum) * (Math.pow(2, winner['FS'] + v['FS']));
                    if (-temp > 80) {
                        temp = -80;
                    }
                    sumScore.push(temp)
                });
            } else if (Spattern == 'DH') {
                if (pattern == Const.Pattern.PAIR7) {
                    others.forEach(function (v) {
                        v['index']._baseScore = 10;
                        var temp = (-10) * (Math.pow(2, winner['FS'] + v['FS']));
                        if (-temp > 80) {
                            temp = -80;
                        }
                        sumScore.push(temp);
                    });
                } else {
                    others.forEach(function (v) {
                        v['index']._baseScore = 10 + (-mqNum);
                        var temp = (-10 + mqNum) * (Math.pow(2, winner['FS'] + v['FS']));
                        if (-temp > 80) {
                            temp = -80;
                        }
                        sumScore.push(temp)
                    });
                }
            } else if (Spattern == 'SDH') {
                if (pattern == Const.Pattern.QISPAIR7 || pattern == Const.Pattern.HHPAIR7) {
                    others.forEach(function (v) {
                        v['index']._baseScore = 20;
                        var temp = (-20) * (Math.pow(2, winner['FS'] + v['FS']));
                        if (-temp > 80) {
                            temp = -80;
                        }
                        sumScore.push(temp);

                    });
                } else {
                    others.forEach(function (v) {
                        v['index']._baseScore = 20 + (-mqNum);
                        var temp = (-20 + mqNum) * (Math.pow(2, winner['FS'] + v['FS']));
                        if (-temp > 80) {
                            temp = -80;
                        }
                        sumScore.push(temp);

                    });
                }
            } else if (Spattern == 'YZM') {
                if (pattern == Const.Pattern.QISPAIR7 || pattern == Const.Pattern.HHPAIR7) {
                    others.forEach(function (v) {
                        v['index']._baseScore = 40;
                        var temp = (-40) * (Math.pow(2, winner['FS'] + v['FS']));
                        if (-temp > 80) {
                            temp = -80;
                        }
                        sumScore.push(temp)
                    });
                } else {
                    others.forEach(function (v) {
                        v['index']._baseScore = 40 + (-mqNum);
                        var temp = (-40 + mqNum) * (Math.pow(2, winner['FS'] + v['FS']));
                        if (-temp > 80) {
                            temp = -80;
                        }
                        sumScore.push(temp)
                    });
                }
            }
            if (sumScore.every(function (v) {
                return -v >= 80;
            })) {
                for (var i = 0; i < sumScore.length; ++i) {
                    sumScore[i] = -100;
                }
            }
            var re = sumScore.reduce(function (a, b) {
                return a + b;
            }, 0);
            winner['index']._score = -re;

            for (var j = 0; j < others.length; ++j) {
                others[j]['index']._score = sumScore[j];
            }

        } else {
            var dpPlayer = this.getPlayerByIndex(from); //点炮玩家
            dpPlayer._isdp = true;
            dpPlayer._stat.dpCount += 1;
            var dp = {
                'index': dpPlayer,
                'FS': this._sumFs(dpPlayer)
            }
            var dpScore = 0;
            var others = [];
            this.enumPlayers(function (eIndex, ePlayer) {
                if (eIndex != playerIndex && !ePlayer.isRoundHu() && eIndex != from) {
                    others.push({
                        'index': ePlayer,
                        'FS': this._sumFs(ePlayer)
                    })
                }
            }.bind(this));

            if (Spattern == 'PH') {
                dp['index']._baseScore = 2;
                var dpScore = (-2) * (Math.pow(2, winner['FS'] + dp['FS']));
                if (-dpScore > 80) {
                    dpScore = -80;
                }
                sumScore.push(dpScore);

                others.forEach(function (v) {
                    v['index']._baseScore = 1;
                    var temp = 0;
                    temp = (-1) * (Math.pow(2, winner['FS'] + v['FS']));
                    if (-temp > 80) {
                        temp = -80;
                    }
                    sumScore.push(temp);
                });
            } else if (Spattern == 'DH') {
                dp['index']._baseScore = 10;
                var dpScore = (-10) * (Math.pow(2, winner['FS'] + dp['FS']))
                if (-dpScore > 80) {
                    dpScore = -80;
                }
                sumScore.push(dpScore);

                others.forEach(function (v) {
                    v['index']._baseScore = 5;
                    var temp = (-5) * (Math.pow(2, winner['FS'] + v['FS']));
                    if (-temp > 80) {
                        temp = -80;
                    }
                    sumScore.push(temp);
                });
            } else if (Spattern == 'SDH') {
                dp['index']._baseScore = 20;
                var dpScore = (-20) * (Math.pow(2, winner['FS'] + dp['FS']))
                if (-dpScore > 80) {
                    dpScore = -80;
                }
                sumScore.push(dpScore);

                others.forEach(function (v) {
                    v['index']._baseScore = 10;
                    var temp = (-10) * (Math.pow(2, winner['FS'] + v['FS']));
                    if (-temp > 80) {
                        temp = -80;
                    }
                    sumScore.push(temp);
                });
            } else if (Spattern == 'YZH') {
                dp['index']._baseScore = 40;
                var dpScore = (-40) * (Math.pow(2, winner['FS'] + dp['FS']))
                if (-dpScore > 80) {
                    dpScore = -80;
                }
                sumScore.push(dpScore);

                others.forEach(function (v) {
                    v['index']._baseScore = 20;
                    var temp = (-20) * (Math.pow(2, winner['FS'] + v['FS']));
                    if (-temp > 80) {
                        temp = -80;
                    }
                    sumScore.push(temp);
                });
            }

            if (sumScore.every(function (v) {
                return -v >= 80;
            })) {
                for (var i = 0; i < sumScore.length; ++i) {
                    sumScore[i] = -100;
                }
            }
            dp['index']._score = sumScore[0];
            var re = sumScore.reduce(function (a, b) {
                return a + b;
            }, 0);
            winner['index']._score = -re;
            for (var i = 1; i < sumScore.length; ++i) {
                others[i - 1]['index']._score = sumScore[i];
            }
        }
        this.broadcastReplay("onPlayerHu", {
            playerIndex: playerIndex,
            card: card,
            from: from,
        });
    },
    //结算处理 _settlementPlayerTing(player)
    // settlementRules() settlementGangScore() 
    //settlementPatternScore()
    //settlement() getSettlementInfo()
    onCurRoundFinished: function () {
        this._super();
        if (this.isRoundHZ()) {
            var settlements = {
                players: {},
                isHZ: this.isRoundHZ(),
            };
            this.enumPlayers(function (eIndex, ePlayer) {
                settlements.players[eIndex] = ePlayer.getSettlementInfo();
            });
            //this.broadcast("onRoundSettlement", settlements);
            logger.debug("room=%d onRoundSettlement=%j", this.rid(), settlements)
        } else {
            // 计算新的庄家
            var oldDealerIndex = this.getDealerIndex();
            var newDealerIndex = oldDealerIndex;
            this.enumPlayers(function (eIndex, ePlayer) {
                if (eIndex == this.huIndex) {
                    newDealerIndex = eIndex;
                }
            }.bind(this));
            //newDealerIndex = this.getNextIndex(oldDealerIndex);
            if (this._dealerIndex != newDealerIndex) {
                this._dealerIndex = newDealerIndex;
                this._dealerLZ = 1;
            } else {
                this._dealerLZ += 1;
            }
        }

        //settlements.finalRound = this.isFinalRound();
        // console.log("结算广播")
        //this.broadcast("onRoundSettlement", settlements);
        //logger.debug("room=%d onRoundSettlement=%j", this.rid(), settlements);

        this.broadcastReplay("onDealerChanged", {
            dealer: this._dealerIndex,
            dealerLZ: this._dealerLZ
        });
    },
    onSettlement: function () {
        //  var isHZ = (this.getHuPlayerCount() == 0); // 是否黄庄
        //
        //  var settlements = {
        //      players: {},
        //     isHZ: this.isRoundHZ(),
        // };
        //
        //
        // this.enumPlayers(function (eIndex, ePlayer) {
        //     settlements.players[eIndex] = ePlayer.getSettlementInfo();
        // });

    },
    onAfterPlayCard: function (player, card, playInfo) {
        this._super(player, card, playInfo);

        player._hundiao = false;
        if (player._hundiao == false) {
            if (player.checkHunDiao(player._handCards.getCards())) {
                player._hundiao = true;
            }
        }
    },
    //检查亮牌
    handlePlaylzCard: function (player, msg, callback) {
        if (!this.isPlaying()) {
            callback({ code: Code.ROOM_NOT_PLAYING }); return;
        }

        if (player.getIndex() != this.getCurPlay()) {
            callback({ code: SubCode.NOT_CUR_PLAY }); return;
        }

        if (this._hangupTask.existOther(player.getIndex())) {
            callback({ code: SubCode.EXIST_OTHER_HANGUP }); return;
        }

        if (isNaN(msg.card)) {
            callback({ code: Code.ARGS_INVALID }); return;
        }

        var card = +msg.card;
        //var code = this.onBeforePlayCard(player, msg, card);
        // if (code) {
        //     callback({ code: code }); return;
        // }

        if (!player.playCard(card)) {
            callback({ code: SubCode.CARD_NOT_EXIST }); return;
        }

        //this._lastPlayIndex = this.getCurPlay()

        // if (msg.ting) {
        //     this.handleCheckAndBaoTing(player, msg, function(resp) {
        //         logger.debug("room=%d index=%d play and ting result:%j", this.rid(), player.getIndex(), resp);
        //     });
        // }

        var playInfo = {
            playerIndex: player.getIndex(),
            card: card
        };
        this.onAfterPlayCard(player, card);
        this.broadcastReplay("onPlayCard", playInfo);
        this._curTask = MJ.Task.PLAY;
        if (this.getHZFCLZG()) {
            if (msg.card == MJ.ZI.HZ || msg.card == MJ.ZI.FC) {
                player.setFS('HZFCG');
            } else if (msg.card == this.getLZCard()) {
                player.setFS('LZG');
            }
        } else {
            if (msg.card == MJ.ZI.HZ) {
                player.setFS('HZFCG');
            } else if (msg.card == this.getLZCard()) {
                player.setFS('LZG');
            }
        }
        //this._hangupTask.reset();
        //this.checkPlayCardHangupTask(card);
        logger.debug("room=%d sendHangupTask in=MJ.handlePlayCard", this.rid());
        this._sendCurPlay();
        this._dealNewCard();
        callback({});
        //this._sendHangupTask(this._nextCurPlay);
    },
    checkLP: function () {
        this.enumPlayers(function (eIndex, ePlayer) {
            var handCards = ePlayer._handCards;
            if (handCards.getCardNum(MJ.ZI.HZ) >= 2 && handCards.getCardNum(MJ.ZI.BB) >= 2 && handCards.getCardNum(MJ.ZI.FC) >= 2) {
                this._LPTask.push({ "Index": eIndex, "Player": ePlayer, "count": 2 });
            }
            else if (handCards.getCardNum(MJ.ZI.HZ) >= 1 && handCards.getCardNum(MJ.ZI.BB) >= 1 && handCards.getCardNum(MJ.ZI.FC) >= 1) {
                this._LPTask.push({ "Index": eIndex, "Player": ePlayer, "count": 1 });
            }
        }.bind(this));

        if (this._LPTask.length != 0) {
            var waitP = []
            this._LPTask.forEach(function (v) {
                v.Player.send('onLP', {});
                waitP.push(v.Player.getIndex());
            });
            this.broadcastReplay("waitLP", { "playerIndex": waitP })
        } else {
            this.broadcastReplay('onFinishLP', {});
            this.startPlay();
        }
    },

    handlePassLP: function (player, msg, callback) {
        if (this._LPTask.length != 0) {
            var index = player.getIndex();
            for (var i = 0; i < this._LPTask.length; ++i) {
                if (this._LPTask[i].Index == index) {
                    this._LPTask.splice(i, 1);
                    break;
                }
            }
        }
        if (this._LPTask.length == 0) {
            this.broadcastReplay('onFinishLP', {});
            this.startPlay();
        }
        callback({});
    },
    handleLP: function (player, msg, callback) {
        //
        if (this._LPTask.length == 0) {
            callback({});
            return;
        }
        if (this._LPTask.length != 0) {
            var index = player.getIndex();

            for (var i = 0; i < this._LPTask.length; ++i) {
                if (this._LPTask[i].Index == index) {
                    if (this.getHZFCLZG()) {
                        if (this.getLZCard() == MJ.ZI.BB) {
                            // player.setFS('LLZ');
                            // player.setFS('ZFLYC');
                            player.setFS('ZFLYCLZ');
                        } else {
                            player.setFS('ZFLYC');
                        }
                        if (this._LPTask[i].count > 1) {

                            this._LPTask[i].count -= 1;
                            player.send('onLP', {});
                            player.liangCard();
                            this.broadcastReplay("onHSLP", {
                                'playerIndex': player.getIndex()
                            });
                            break;
                        } else {

                            this._LPTask.splice(i, 1);
                            player.liangCard();
                            this.broadcastReplay("onHSLP", {
                                'playerIndex': player.getIndex()
                            });
                            break;
                        }

                    } else {
                        if (this.getLZCard() == MJ.ZI.FC || this.getLZCard() == MJ.ZI.BB) {
                            // player.setFS('LLZ');
                            // player.setFS('ZLYC');
                            player.setFS('ZLYCLZ');
                        } else {
                            player.setFS('ZLYC');
                        }

                        if (this._LPTask[i].count > 1) {
                            this._LPTask[i].count -= 1;
                            player.send('onLP', {});
                            player.liangCard();
                            this.broadcastReplay("onHSLP", {
                                'playerIndex': player.getIndex()
                            });
                            break;
                        } else {
                            this._LPTask.splice(i, 1);
                            player.liangCard();
                            this.broadcastReplay("onHSLP", {
                                'playerIndex': player.getIndex()
                            });
                            break;
                        }
                    }
                }
            }
        }
        if (this._LPTask.length == 0) {
            callback({});

            this.broadcastReplay('onFinishLP', {});
            this.startPlay();
            return;
        }
        callback({});
    },
    handleSetGPS: function (player, msg, callback) {
        if (msg.gps) {
            player._gps = msg.gps;
        }
        callback({});
        this.broadcast("onGPSchange", {
            "playerIndex": player.getIndex(),
            "gps": msg.gps
        });
    },

    SetLZP: function () {

        if (this.getLZCard() == 0) {
            this._setLZCard();
            // var info = {};
            var lz = [];
            if (this.getHZFCLZG()) {
                lz.push(this._LZCard)
                lz.push(MJ.ZI.HZ);
                lz.push(MJ.ZI.FC);
            } else {
                lz.push(this._LZCard)
                lz.push(MJ.ZI.HZ);
            }

            this.broadcastReplay("onGetLZ", { 'lz': lz });
            this.initPlayersHandCards();
            this.checkLP();
        } else {
            this.broadcastReplay("onFinishLP", {});
            this.startPlay();

        }
    },
    handleEnjoy: function (player, msg, callback) {
        var gameConfig = this.getGameConfig();
        var giftType = msg.message.type.id;
        var giftConfig = null;
        giftConfig = gameConfig.Enjoy[giftType];
        var costMode = this.getCostMode();

        if (!giftConfig) {
            callback({ code: Code.ARGS_VALUE_WRONG }); return;
        }
        if (!this.giftcost) {
            this._canCost();
        }
        if (costMode == Def.RoomCostMode.CREATOR) {
            if (player.uid() == this.getCreator()) {
                var cost = ExObject.merge({}, this.giftcost, giftConfig.costs)
                if (!player.checkResource(cost)) {
                    callback({ code: Code.LACK_OF_RESOURCE }); return;
                }
                msg.playerIndex = player.getIndex();
                this.broadcast("onRoomChat", msg);
                player.costResourceSync(giftConfig.costs);
                callback({});
                return;
            }
            if (!player.checkResource(giftConfig.costs)) {
                callback({ code: Code.LACK_OF_RESOURCE }); return;
            }
            player.costResourceSync(giftConfig.costs);
            msg.playerIndex = player.getIndex();
            this.broadcast("onRoomChat", msg);
            callback({});
            return;
        }
        var cost = ExObject.merge({}, this.giftcost, giftConfig.costs)
        if (!player.checkResource(cost)) {
            callback({ code: Code.LACK_OF_RESOURCE }); return;
        }
        msg.playerIndex = player.getIndex();
        this.broadcast("onRoomChat", msg);
        player.costResourceSync(giftConfig.costs);
        callback({});
    },
    _canCost: function () {
        var costMode = this.getCostMode();
        switch (costMode) {
            case Def.RoomCostMode.AA:
                var SubLogic = this.getLogicModule();
                var needResource = gameUtil.calcCreateRoomNeedResource(SubLogic, this.getInitArgs());
                var aaNeedResource = ExObject.mulNew(needResource, 1 / this.getMaxPlayer(), Math.ceil);
                this.giftcost = aaNeedResource;
                break;
            default:
                var NeedResource = gameUtil.calcCreateRoomNeedResource(this.getLogicModule(), this.getInitArgs());
                this.giftcost = NeedResource;
                break;
        }
    },
    /******************************************************************
     * 功能接口
     ******************************************************************/

    /**
     * 结算玩家是否听牌
     * @param player
     * @private
     * 
     * isRoundTing()
     * checkTing()
     * setRoundPattern(pattern, 0)
     */
    _settlementPlayerTing: function (player) {
        //已听牌玩家不用再检测
        if (player.isRoundTing()) {
            return;
        }

        // 对未胡牌的玩家检查是否听牌
        var tings = player.checkTing();
        var pattern = Const.Pattern.NONE;
        var patternScore = 0;
        for (var i = 0; i < tings.length; ++i) {
            var ting = tings[i];
            var score = Const.PatternScore[ting.pattern];
            if (score > patternScore) {
                pattern = ting.pattern;
                patternScore = score;
            }
        }
        player.setRoundPattern(pattern, 0);
    },
    //随机获取一张牌
    getRandomCard: function () {
        var index = ExNumber.rand(this._publicCards.cards.length);
        var card = this._publicCards.cards[index];
        return card;
    },
    //获取玩家赖子数量
    getLZCardNum: function (player) {
        return player._handCards.getCardNum(this.getLZCard());
    },
});